#include "Particle.h"
#include "Resources.h"
#include "Environment.h"
extern Environment env;

Particle::Particle(ofPoint loc, ofPoint vel, float ttl) : ttl(ttl) {
    t_created = ofGetElapsedTimef();
    this->loc = loc;
    this->vel = vel;
}

bool Particle::update() {
    return positionAndTtlUpdate();
}

bool Particle::positionAndTtlUpdate() {
    t_elapsed = ofGetElapsedTimef() - t_created;

    if (!env.wgrid()[(int)loc.y][(int)(loc.x+vel.x)]->transparent)
        vel.x *= -0.3f;

    loc.x += vel.x;

    if (!env.wgrid()[(int)(loc.y+vel.y)][(int)loc.x]->transparent) {
        vel.y *= -0.3f;
        vel.x *= 0.75f;
    }

    if (fabs(vel.y) < 0.03f) vel.y = 0.0f;
    loc.y += vel.y;

    vel.y -= 0.03f;

    if (t_elapsed > ttl) return true;
    return false;
}

void Particle::draw() {
    float rmax = 0.09f;
    float r = ofClamp(((ttl-(ofGetElapsedTimef()-t_created))/ttl)*rmax, 0, rmax);
    float a = ofClamp(255*(r/rmax), 0, 255); // 2550 = 10*255 ; basically, scaling alpha to zero over the life of the particle.
    ofEnableAlphaBlending();
    ofSetColor(color.r, color.g, color.b, a);
    ofCircle(loc.x, loc.y+r/2, r);
    ofSetColor(0, 0, 0, a);
    ofEnableSmoothing();
    ofNoFill();
    ofCircle(loc.x, loc.y+r/2, r);
    ofFill();
    ofDisableSmoothing();
    ofDisableAlphaBlending();
}

void Particle::setColor(int r, int g, int b) {
    color.r = r;
    color.g = g;
    color.b = b;
}

void Particle::setColor(int color) {
    int r = (color & 0xFF0000) >> 16;
    int g = (color & 0x00FF00) >> 8;
    int b = (color & 0x0000FF);

    setColor(r, g, b);
}
